﻿using AutoMapper;
using B.S.Medical.Api.Write.Application.Command.Register;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;

namespace B.S.Medical.Api.Write.Application.Handler.Register
{
    /// <summary>
    /// 新增预约须知实现层
    /// </summary>
    public class AddAppointmentNoticeHandler : IRequestHandler<AddAppointmentNoticeCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AppointmentNoticeModel> _appointmentNoticeRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddAppointmentNoticeHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        public AddAppointmentNoticeHandler(IBaseRepository<AppointmentNoticeModel> appointmentNoticeRepository, IMapper mapper, ILogger<AddAppointmentNoticeHandler> logger)
        {
            _appointmentNoticeRepository = appointmentNoticeRepository;
            _mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 新增预约须知
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回统一包装类</returns>
        public async Task<ApiResult<int>> Handle(AddAppointmentNoticeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            try
            {
                var appointmentNotice = _mapper.Map<AppointmentNoticeModel>(request);
                appointmentNotice.IsDeleted = false;

                var r = await _appointmentNoticeRepository.CreateAsync(appointmentNotice);
                if (r > 0)
                {
                    res.Msg = "新增预约须知成功!";
                    res.Code = ApiEnum.Success;
                    _logger.LogInformation($"新增预约须知成功，ID: {r}");
                    res.Data = r;
                }
                else
                {
                    res.Msg = "新增预约须知失败!";
                    res.Code = ApiEnum.Fail;
                    _logger.LogError($"新增预约须知失败");
                    res.Data = r;
                }
                return await Task.FromResult(res);
            }
            catch (Exception ex)
            {
                res.Msg = "新增预约须知异常"+ex.Message;
                res.Code = ApiEnum.Fail;
                _logger.LogError($"新增预约须知异常"+ex.Message);
                return await Task.FromResult(res);
            }
        }
    }
}
